<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable style="width: 200px">
          <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="当前阶段" prop="phaseCode">
        <el-input v-model="queryParams.phaseName" placeholder="请输入当前阶段" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="预计验收日期" style="width: 308px">
        <el-date-picker v-model="daterangeAcceptTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="立项金额">
        <div style="display: flex; align-items: center;">
          <el-input v-model="queryParams.minProjectAmount" placeholder="最小金额" clearable @keyup.enter="handleQuery"
            style="width: 120px; margin-right: 10px;" />
          -
          <el-input v-model="queryParams.maxProjectAmount" placeholder="最大金额" clearable @keyup.enter="handleQuery"
            style="width: 120px; margin-left: 10px;" />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>

        <!-- <el-button type="primary" icon="Search" @click="handleSync">同步数据</el-button> -->
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="projectList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目编号" align="center" width="180" prop="projectNo" />
      <el-table-column label="项目名称" align="center" width="200" prop="projectName" />
      <el-table-column label="发起人" align="center" prop="createUserName" />
      <el-table-column label="发起人所在部门" align="center" width="120" prop="createDeptName" />
      <el-table-column label="合同金额" align="center" show-overflow-tooltip width="200" prop="contractAmount" />
      <el-table-column label="结算金额" align="center" show-overflow-tooltip width="200" prop="settlementAmount" />
      <el-table-column label="项目类型" align="center" width="120" prop="projectType">
        <template #default="scope">
          <dict-tag :options="project_type" :value="scope.row.projectType" />
        </template>
      </el-table-column>
      <el-table-column label="项目配合单位" align="center" prop="projectUnit" />
      <el-table-column label="发起时间" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计验收日期" align="center" prop="acceptTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.acceptTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="立项日期" align="center" prop="approvalDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.approvalDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结算金额" align="center" show-overflow-tooltip width="200" prop="settlementAmount" />

      <el-table-column label="客户地址" align="center" show-overflow-tooltip width="200" prop="customerAddress" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="管家婆项目" align="center" prop="housekeeperName" show-overflow-tooltip width="300" />
      <!-- <el-table-column label="当前阶段" align="center" prop="phaseName" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" fixed="right" width="220" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button> -->
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">添加</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改绩效基本信息对话框 -->
    <el-dialog :title="title" fullscreen v-model="open" width="800px" append-to-body>
      <projectView :datas="form" :column="3" :sizes="'large'"></projectView>

      <!-- <el-form ref="projectRef" v-show="false" :disabled="formDisabled" :model="form" label-position="left"
        :rules="rules" label-width="120px" size="large">
        <el-row :gutter="21">
          <el-col :span="7">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="项目配合单位" prop="projectUnit">
              <el-input v-model="form.projectUnit" placeholder="请输入项目配合单位" />
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="项目类型" prop="projectType">
              <el-select @change="setProjectTypeName" v-model="form.projectType" placeholder="请选择项目类型"
                style="width: 200px;">
                <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="21">
          <el-col :span="7">
            <el-form-item label="发起人" prop="createDeptName">
              <el-input disabled v-model="form.createUserName" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="发起人所在部门" prop="createDeptName">
              <el-input disabled v-model="form.createDeptName" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="发起时间" prop="startDate">
              <el-date-picker disabled clearable v-model="form.startDate" type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发起时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="21">
          <el-col :span="7">
            <el-form-item label="立项金额(元)" prop="projectAmount">
              <el-input type="number" @wheel.native.prevent v-model="form.projectAmount" placeholder="请输入立项金额">
              </el-input>
            </el-form-item>
          </el-col>


          <el-col :span="7">
            <el-form-item label="合同金额(元)" prop="contractAmount">
              <el-input type="number" @wheel.native.prevent v-model="form.contractAmount" placeholder="请输入合同金额">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="结算金额(元)" prop="settlementAmount">
              <el-input type="number" @wheel.native.prevent v-model="form.settlementAmount" placeholder="请输入结算金额">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="21">

          <el-col :span="7">
            <el-form-item label="管家婆项目" prop="housekeeperProject">
              <el-select-v2 filterable v-model="form.housekeeperProject" clearable :options="companyList"
                placeholder="请选择，支持输入名称搜索" style="width: 100%" @change="setHousekeeperName" />
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="预计验收日期" prop="acceptTime">
              <el-date-picker clearable v-model="form.acceptTime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择预计验收日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span=7>
            <el-form-item label="立项日期" prop="approvalDate">
              <el-date-picker clearable v-model="form.approvalDate" type="date" value-format="YYYY-MM-DD"
                placeholder="立项日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="21">

          <el-col :span="7">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>

          <el-col :span="14">
            <el-form-item label="客户地址" prop="customerAddress">
              <el-input v-model="form.customerAddress" placeholder="请输入客户地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>


        <el-divider style="font-size: 16px; font-weight: bold;">参与人员信息111</el-divider>
        <el-button type="primary" plain :icon="Plus" @click="addPerson()"
          style="margin-bottom: 10px;">添加参与人员11111</el-button>
        <el-table v-loading="loading" :data="personList" border @selection-change="handleSelectionChange">
          <el-table-column label="标签页" align="center" width="180" prop="phaseName" />
          <el-table-column label="参与人" align="center" width="200" prop="participanName" />
          <el-table-column label="岗位" align="center" prop="postName" />
          <el-table-column label="开始日期" align="center" width="120" prop="startDate" />
          <el-table-column label="结束日期" align="center" prop="endDate" />
          <el-table-column label="备注" align="center" width="120" prop="remark" />
          <el-table-column label="操作员" align="center" prop="operator" />
          <el-table-column label="操作时间" align="center" prop="startDate" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="220" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdateParticipan(scope.row)">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDeleteParticipan(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form> -->

      <el-divider style="font-size: 16px; font-weight: bold;">参与人员信息</el-divider>
      <el-button :disabled="!haveAddPerson" type="primary" plain :icon="Plus" @click="addPerson()" style="margin-bottom: 10px;">添加参与人员</el-button>
      <el-table v-loading="loading" :data="personList" border @selection-change="handleSelectionChange">
        <el-table-column label="标签页" align="center" width="180" prop="phaseName" />
        <el-table-column label="参与人" align="center" width="200" prop="participanName" />
        <el-table-column label="岗位" align="center" prop="postName" />
        <el-table-column label="开始日期" align="center" width="120" prop="startDate" />
        <el-table-column label="结束日期" align="center" prop="endDate" />
        <el-table-column label="备注" align="center" width="120" prop="remark" />
        <el-table-column label="操作员" align="center" prop="operator" />
        <el-table-column label="操作时间" align="center" prop="startDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="220" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button :disabled="!haveAddPerson" link type="primary" icon="Edit" @click="handleUpdateParticipan(scope.row)">修改</el-button>
            <el-button  :disabled="!haveAddPerson" link type="primary" icon="Delete" @click="handleDeleteParticipan(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-divider style="font-size: 16px; font-weight: bold;">附件信息</el-divider>
      <el-button type="primary" plain :icon="Plus" @click="addFiles()" style="margin-bottom: 10px;">添加附件信息</el-button>
      <el-table v-loading="loading" :data="attachmentList" border @selection-change="handleSelectionChange">
        <el-table-column label="标签页" align="center" prop="phaseName" />
        <el-table-column label="附件类别" align="center" prop="attachmentType">
          <template #default="scope">
            <dict-tag :options="file_type" :value="scope.row.attachmentType" />
          </template>
        </el-table-column>
        <el-table-column label="附件标题" align="center" prop="attachmentTitle" />
        <el-table-column label="附件名称" align="center" show-overflow-tooltip width="200" prop="fileName">
          <template #default="scope">
            <el-link type="primary" @click="downloadFile(scope.row)">{{ scope.row.fileName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="操作员" align="center" prop="operator" />
        <el-table-column label="操作时间" align="center" prop="startDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="220" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdateFile(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDeleteFile(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 是否有 超级管理员 项目经理 销售 销售负责人 商务 财务权限之一  -->
      <div>
        <el-divider style="font-size: 16px; font-weight: bold;">实施日志信息</el-divider>
        <el-button type="primary" plain :icon="Plus" @click="addImplements()" style="margin-bottom: 10px;">添加实施工作日志</el-button>
        <el-table v-loading="loading" border :data="implementList" @selection-change="handleSelectionChange">
      <!-- <el-table-column label="关联的阶段id" align="center" prop="phaseId" /> -->
      <el-table-column label="实施日期" align="center" prop="implementDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.implementDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="附件照片" align="center" prop="images" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.images" v-if="scope.row.images" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="附件" align="center" prop="files" /> -->
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="内容" align="center" prop="remark" />
      <!-- <el-table-column label="文件名称" align="center" prop="fileName" /> -->
      <el-table-column label="文件类型" align="center" prop="fileType">
        <template #default="scope">
          <dict-tag :options="log_type" :value="scope.row.fileType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column label="操作时间" align="center" prop="startDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
          </template>
        </el-table-column>
 
      <el-table-column label="操作" align="center" fixed="right" width="220"  class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdateImplement(scope.row)" >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDeleteImplement(scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitForm(1)">保存当前内容</el-button> -->
          <el-button type="primary" v-if="status == 1"@click="nextPhase()">下一步</el-button>
          <el-button  type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改项目参加人员子对话框 -->
    <el-dialog :title="title" v-model="openOper" width="800px" append-to-body>
      <el-form ref="participanRef" :model="personForm" :rules="personRules" label-width="120px">
        <el-form-item label="参与人" prop="participantId">
          <el-select @change="setPersonName" filterable v-model="personForm.participantId" placeholder="请选择参与人"
            clearable style="width: 200px;">
            <el-option v-for="dict in userList" clearable :key="dict.userId" :label="dict.nickName"
              :value="dict.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与人岗位" prop="postId">
          <el-select @change="setPostName" filterable v-model="personForm.postId" placeholder="请选择岗位" clearable
            style="width: 200px;">
            <el-option v-for="dict in posts" clearable :key="dict.postId" :label="dict.postName"
              :value="dict.postId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable v-model="personForm.startDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable v-model="personForm.endDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="personForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPersonForm">确 定</el-button>
          <el-button @click="cancelPerson">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 添加或修改附件对话框 -->
    <el-dialog title="附件信息" v-model="openFile" width="500px" append-to-body>
      <el-form ref="attachmentRef" :model="fileForm" :rules="fileRules" label-width="80px">
        <el-form-item label="附件类别" prop="attachmentType">
          <el-select v-model="fileForm.attachmentType" placeholder="请选择附件类别">
            <el-option v-for="dict in file_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附件标题" prop="attachmentTitle">
          <el-input v-model="fileForm.attachmentTitle" placeholder="请输入附件标题" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="fileForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="上传附件" prop="filePath">
          <file-upload :limit="1" v-model="fileForm.filePath" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="cancelFile">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改付款对话框 -->
    <el-dialog title="付款信息" v-model="openImplement" width="800px" append-to-body>
      <el-form ref="implementRef" size="large" :model="implementForm" :rules="ImplementRules" label-width="120px">

        <!-- <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item width="200" label="付款公司" prop="company">
              <el-input v-model="implementForm.company" placeholder="请输入付款公司" />
            </el-form-item>
          </el-col>
        </el-row> -->

        
        <el-form-item label="实施日期" prop="implementDate">
          <el-date-picker clearable
            v-model="implementForm.implementDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择实施日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="附件类型" prop="fileType">
          <el-select v-model="implementForm.fileType" placeholder="请选择附件类型">
            <el-option
              v-for="dict in log_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="implementForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="remark">
          <el-input v-model="implementForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
   
        <el-form-item label="附件照片" prop="images">
          <image-upload v-model="implementForm.images"/>
        </el-form-item>
        <!-- <el-form-item label="附件" prop="files">
          <file-upload v-model="implementForm.files"/>
        </el-form-item> -->


     
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitimplementForm">确 定</el-button>
          <el-button @click="canceImplement">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改绩效基本信息对话框 -->
    <el-dialog v-model="openView" width="1000px" append-to-body>
      <projectView :datas="form" :column="2" :sizes="'large'"></projectView>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Project">
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
  syncData,
  getCompanyList,
  getFinanceList,
  listParticipan, getParticipan, delParticipan, addParticipan, updateParticipan, getPermission,
  getStatus,
  listImplement, getImplement, delImplement, addImplement, updateImplement
} from "@/api/project/project";
import { listAttachment, getAttachment, delAttachment, addAttachment, updateAttachment } from "@/api/project/project";
import {  listPhase, getPhase, delPhase, addPhase, updatePhase } from "@/api/project/project";
import {
  Plus
} from '@element-plus/icons-vue'
import { listDictionary } from "@/api/project/dictionary.js";
import { getInfo } from "@/api/login";
import { listAllUser, getUser, getPosts } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { project_type } = proxy.useDict("project_type");
const { phase_type } = proxy.useDict("phase_type");
const { file_type } = proxy.useDict('file_type');
const { log_type } = proxy.useDict('log_type');
const attachmentList = ref([]);
const implementList = ref([]);
const posts = ref([])
const userList = ref([])
const projectList = ref([]);
const personList = ref([]);
const companyList = ref([]);
const financeList = ref([]);
const open = ref(false);
const openView = ref(false);
const openOper = ref(false);
const openPhase = ref(false);
const openFile = ref(false);
const openImplement = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const projectNo = ref("")
const contractAmount = ref(0)
const finance = ref(false);//当期人员是否是财务
const isAdmin = ref(false);//是否是超级管理员
const haveImplement = ref(false);//是否有添加实施日志信息的权限
const haveAddPerson = ref(false);//是否有添加参与人员的权限
const status = ref("0");
const currenrPhaseId = ref()
function fileChange(file) {
  console.log("上传文件：", file);

}


const phasetList = ref([]);
const formDisabled = ref(true);
let currentPhase = reactive({
  phaseCode: '',
});
import projectView from "../projectView.vue";
import { ref } from "vue";
import { pa } from "element-plus/es/locale/index.mjs";
const data = reactive({
  currentProject: {},
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  personForm: {
  },
  fileForm: {

  },
  implementForm: {

  },

  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status:2,//写死 查询上个阶段已完成的就进入立项前期阶段 1是进行中 2是已完成 
              // 新建项目的时候会默认插入一条立项阶段到立项表 点击下一步的时候会更新阶段表把当前项目当前阶段的状态
              //改为已完成  同时往阶段表插入下一个阶段 状态是1 进行中
    phaseId:2,//阶段字典id   0是立项 1是立项前期 2是实施 3是项目绩效 .....现在是绩效阶段 查询所有实施已完成的项目
   
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperName: null,
    phaseCode: null,
    minProjectAmount: null,
    maxProjectAmount: null
  },
  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    approvalDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
    projectType: [{ required: true, message: "项目类型 不能为空", trigger: "blur" }],
  },
  personRules: {
    postId: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
    participantId: [{ required: true, message: "参与人不能为空", trigger: "blur" }],
  },

  fileRules: {
    // postId: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
    // participantId: [{ required: true, message: "参与人不能为空", trigger: "blur" }],
  },

  ImplementRules: {
    // postId: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
    // participantId: [{ required: true, message: "参与人不能为空", trigger: "blur" }],
  }





});


function handleBlur(type) {
  if (type == 1) {
    const percentage = parseFloat(implementForm.value.percentage);
    console.log(`付款百分比为: ${percentage}%`);
    // 计算金额并保留两位小数
    implementForm.value.amount = parseFloat((percentage / 100 * implementForm.value.totalAmount).toFixed(2));
    console.log(`计算后的金额为: ${implementForm.amount}`);
  } else {
    const percentage = parseFloat(implementForm.value.percentage);

    console.log(`付款百分比为: ${percentage}%`);
    // 计算金额并保留两位小数
    implementForm.value.receivedPercentage = parseFloat((implementForm.value.receivedAmount / implementForm.value.totalAmount * 100 ).toFixed(2));
    console.log(`百分比: ${implementForm.value.receivedPercentaget}`);
  }

}

// import {getPermission} from "@/api/project/project";
async function downloadFile(row) {
  //只有项目经理 销售负责人 吴总 能够下载正式清单 竣工结算清单 正式合同
  if (row.attachmentType == '4' || row.attachmentType == '5' || row.attachmentType == '22') {
    let params = {
      projectNo: row.projectNo,
      postIds: [2, 5,6,7]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
    }
    const res = await getPermission(params).then((response) => {
      console.log("下载附件", response.data);
      return response.data
    });
    if (!res) {
      proxy.$modal.msgError("暂无权限下载此附件");
      return
    }
  }

  var name = row.fileName;
  var url = row.filePath || row.files;
  // var suffix = url.substring(url.lastIndexOf("."), url.length);
  const a = document.createElement('a')
  a.setAttribute('download', name)
  a.setAttribute('target', '_blank')
  a.setAttribute('href', import.meta.env.VITE_APP_BASE_API + url)
  a.click()
}


/** 修改按钮操作 */
function handleUpdateFile(row) {
  resetFile();
  const _attachmentId = row.attachmentId || ids.value
  getAttachment(_attachmentId).then(response => {
    fileForm.value = response.data;
    openFile.value = true;
  });
}
/** 修改付款信息按钮操作 */
function handleUpdateImplement(row) {
  resetImplement();
  const _Id = row.id || ids.value
  getImplement(_Id).then(response => {
    implementForm.value = response.data;
    openImplement.value = true;
  });
}

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}

/** 提交按钮 */
function submitFileForm() {
  proxy.$refs["attachmentRef"].validate(valid => {
    if (valid) {
      fileForm.value.fileName = getFileName(fileForm.value.filePath)
      fileForm.value.projectNo = projectNo.value
      if (fileForm.value.attachmentId != null) {
        updateAttachment(fileForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openFile.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addAttachment(fileForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openFile.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}


/** 提交按钮 */
function submitimplementForm() {
  proxy.$refs["implementRef"].validate(valid => {
    if (valid) {
      implementForm.value.projectNo = projectNo.value
      // implementForm.value.fileName = getFileName(implementForm.value.files)
      if (implementForm.value.id != null) {
        updateImplement(implementForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openImplement.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addImplement(implementForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openImplement.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}



/** 删除按钮操作 */
function handleDeleteFile(row) {
  const _attachmentIds = row.attachmentId || ids.value;
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delAttachment(_attachmentIds);
  }).then(() => {
    getListParticipan(projectNo.value)
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}


/** 删除付款信息按钮操作 */
function handleDeleteImplement(row) {
  const _Id = row.id
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delImplement(_Id);
  }).then(() => {
    getListParticipan(projectNo.value)
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}



//添加参与人员
function addPerson() {
  //重置表单
  resetPer()
  // personList.value = []
  openOper.value = true
  title.value = "添加参与人员信息";
  //项目立项前期 字典值为1 写死
  const filteredObjects = phase_type.value.filter((obj) => obj.value == 1);
  console.log("添加参与人员信息", filteredObjects);
  personForm.value.phaseName = filteredObjects[0]?.label
  personForm.value.phaseId = filteredObjects[0]?.value
}


//添加附件信息
function addFiles() {
  //重置表单
  resetFile()
  // personList.value = []
  openFile.value = true
  title.value = "添加附件信息";
  //项目立项前期 字典值为1 写死
  const filteredObjects = phase_type.value.filter((obj) => obj.value == 1);
  console.log("添加参与人员信息", filteredObjects);
  fileForm.value.phaseName = filteredObjects[0]?.label
  fileForm.value.phaseId = filteredObjects[0]?.value
}
//添加实施日志信息 销售负责人添加实施日志信息？
function addImplements() {
  //校验是否是销售负责人？
  // //立项前期阶段 需要添加项目经理id 2 销售 9 商务 7 财务 6
  // result = attachmentList.value.find(item => item.postId === 2);
  //重置表单
  resetImplement()
  implementForm.value.totalAmount = contractAmount.value//合同签订金额自动带出
  // personList.value = []
  openImplement.value = true
  //项目立项前期 字典值为1 写死
  const filteredObjects = phase_type.value.filter((obj) => obj.value == 1);
  implementForm.value.phaseName = filteredObjects[0]?.label
  implementForm.value.phaseId = filteredObjects[0]?.value
}


const { queryParams, form, rules, personForm, personRules, fileRules, ImplementRules, fileForm, implementForm } = toRefs(data);

const setHousekeeperName = (id) => {
  console.log("setHousekeeperName", id);
  if (id == undefined) {
    form.value.ousekeeperName = '';
    return
  }
  const filteredObjects = companyList.value.find((obj) => obj.id === id);
  form.value.ousekeeperName = '';
  console.log("filteredObjects", filteredObjects);
  form.value.housekeeperName = filteredObjects?.companyName || '';
}

function getCurrUser(id) {
  getPosts(id).then(response => {
    console.log("66666666", response);


  });
}


//判断是否是销售负责人 项目经理 销售 财务 商务

async function isSale() {
  let params = {
    projectNo: projectNo.value,
    phaseId: 2,//项目实施 写死
    postIds: [2, 5]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  // haveImplement.value = await hasPermisson(params)
  haveAddPerson.value = await hasPermisson(params)
  console.log("添加信息", haveAddPerson.value);

}

//是否是财务
async function isFinance() {
  let params = {
    projectNo: projectNo.value,
    phaseId: 1,//立项前期 写死
    postIds: [2, 6]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  finance.value = await hasPermisson(params)

  console.log("添加财务信息", finance.value);
}

async function hasPermisson(params) {
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  return res
}


// function getPhaseStatus(){
//   getStatus
// }

function initData() {
  getUser().then(response => {
    posts.value = response.posts;
    console.log("岗位信息", response);
  });
  listAllUser().then(res => {
    console.log("userlist", res);
    userList.value = res
  });

  getInfo().then((res) => {
    console.log("当前用户", res);
    getCurrUser(res.user.userId)
  })
    .catch((error) => {
      console.log("error", error);
    });
}

const setProjectTypeName = (datas) => {
  //对应的名称
  const filteredObjects = project_type.value.filter((obj) => datas.includes(obj.value));
  form.value.projectTypeName = '';
  const labels = filteredObjects.map((obj) => obj.label);
  form.value.projectTypeName = labels.length > 1 ? labels.join(',') : labels[0] || '';

};



/** 查询绩效基本信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeAcceptTime && "" != daterangeAcceptTime) {
    // queryParams.value.params["beginAcceptTime"] = daterangeAcceptTime.value[0];
    // queryParams.value.params["endAcceptTime"] = daterangeAcceptTime.value[1];
    queryParams.value.beginAcceptTime = daterangeAcceptTime.value[0];
    queryParams.value.endAcceptTime = daterangeAcceptTime.value[1];
  }
  listProject(queryParams.value).then((response) => {
    console.log("response", response);
    projectList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
    console.log('projectList', projectList);

  });
}

// 取消按钮
function cancel() {
  open.value = false;
  openView.value = false
  reset();
}
// 取消按钮
function cancelPerson() {
  openOper.value = false;
  resetPer();
}

// 取消按钮
function cancelFile() {
  openFile.value = false;
  resetFile();
}


// 取消按钮
function canceImplement() {
  openImplement.value = false;
  resetImplement();
}


//获取用户详细信息
function getUserInfo() {
  getInfo().then((res) => {
    const user = res.user;
    form.value.createUserName = user.nickName;
    form.value.createUserId = user.userId;
    form.value.createDeptName = user.dept.deptName
    form.value.createDept = user.deptId
    console.log("user", form);
  })
    .catch((error) => {
      console.log("error", error);
    });


  // listDictionary().then(response => {
  //   form.value.phaseName = response.data?.rows[0]?.phaseName
  //   form.value.phaseCode = response.data?.rows[0]?.phaseCode
  // });

}
// 表单重置 
function reset() {
  form.value = {
    projectNo: null,
    projectName: null,
    createDeptName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerAddress: null,
    customerName: null,
    housekeeperProject: null,
    phaseCode: null,
    remark: null,
    minProjectAmount: null,
    maxProjectAmount: null
  };
  proxy.resetForm("projectRef");
}

// 表单重置
function resetPer() {
  personForm.value = {
    // projectNo: null,
    // projectName: null,
    // createDeptName: null,
    // projectAmount: null,
    // projectType: null,
    // projectUnit: null,
    // acceptTime: null,
    // customerAddress: null,
    // customerName: null,
    // housekeeperProject: null,
    // phaseCode: null,
    // remark: null,
    // minProjectAmount: null,
    // maxProjectAmount: null
  };
  proxy.resetForm("participanRef");

}

// 表单重置
function resetFile() {
  fileForm.value = {
    // projectNo: null,
    // projectName: null,
    // createDeptName: null,
    // projectAmount: null,
    // projectType: null,
    // projectUnit: null,
    // acceptTime: null,
    // customerAddress: null,
    // customerName: null,
    // housekeeperProject: null,
    // phaseCode: null,
    // remark: null,
    // minProjectAmount: null,
    // maxProjectAmount: null
  };
  proxy.resetForm("attachmentRef");

}

// 表单重置
function resetImplement() {
  implementForm.value = {
    // projectNo: null,
    // projectName: null,
    // createDeptName: null,
    // projectAmount: null,
    // projectType: null,
    // projectUnit: null,
    // acceptTime: null,
    // customerAddress: null,
    // customerName: null,
    // housekeeperProject: null,
    // phaseCode: null,
    // remark: null,
    // minProjectAmount: null,
    // maxProjectAmount: null
  };
  proxy.resetForm("implementRef");

}



/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


/** 同步数据 */
function handleSync() {
  syncData().then((response) => {
    proxy.$modal.msgSuccess("同步成功");
  });
}




/** 重置按钮操作 */
function resetQuery() {
  daterangeAcceptTime.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.minProjectAmount = null
  queryParams.value.maxProjectAmount = null
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.projectNo);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function setPostName(id) {
  // 筛选 posts.value 中符合条件的对象
  const filteredObjects = posts.value.filter((obj) => obj.postId === id);
  // 清空 projectTypeName 字段
  personForm.value.postName = '';
  console.log("postName", filteredObjects);
  personForm.value.postName = filteredObjects[0].postName
}

function setPersonName(id) {
  // 筛选 posts.value 中符合条件的对象
  const filteredObjects = userList.value.filter((obj) => obj.userId === id);
  // 清空 projectTypeName 字段
  personForm.value.participanName = '';
  console.log("filteredObjects[0]?.nickName", filteredObjects[0]?.nickName);

  personForm.value.participanName = filteredObjects[0]?.nickName
}


/** 新增按钮操作 */
function handleAdd() {
  formDisabled.value = false
  reset();
  personList.value = []
  open.value = true;
  title.value = "添加项目基本信息";
  form.value.startDate = getCurrentDateTime()
  form.value.approvalDate = getCurrentDate()
  getUserInfo()
}

/** 添加立项前期信息 */
function handleUpdate(row) {
  reset();
  const _projectNo = row.projectNo || ids.value;
  projectNo.value = row.projectNo //存放项目id
  contractAmount.value = row.contractAmount
  getProject(_projectNo).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目基本信息";
  });
  getListParticipan(row.projectNo)
}


function getListParticipan(projectNo) {
  console.log("projectNoprojectNo", projectNo);

  let params = {
    projectNo: projectNo
  }
  listParticipan(params).then((response) => {
    console.log("response", response);
    personList.value = response.data
  });

  listAttachment(params).then((response) => {
    attachmentList.value = response.data;
  });


  listImplement(params).then((response) => {
    implementList.value = response.data;
  });

  isFinance()
  isSale()

  let currPhase = {
    projectNo: projectNo,
    phaseId:1
  }

  getCurrPhase(projectNo)

}


function handleUpdateParticipan(row) {
  // const _projectNo = row.projectNo || ids.value;
  // personForm.projectNo = row.projectNo
  // getProject(_projectNo).then((response) => {
  //   form.value = response.data;
  //   open.value = true;
  //   title.value = "修改基本信息";
  // });
  openOper.value = true
  personForm.value = row

}


function handleDeleteParticipan(row, index) {
  proxy.$modal
    .confirm('是否确认删除？')
    .then(async () => {
      if (row.id) {
        await delParticipan(row.id)
        proxy.$modal.msgSuccess("删除成功");
      }
      getListParticipan(form.value.projectNo)
    })
    .catch((error) => {
      // 捕获错误并提示用户
      console.error("删除操作失败", error);
      proxy.$modal.msgError("删除失败，请稍后再试");
    });
}



/** 阶段管理操作 */
async function handleView(row) {
  formDisabled.value = true
  reset();
  const _projectNo = row.projectNo || ids.value;
  await getProject(_projectNo).then((response) => {
    form.value = response.data;
  });
  openView.value = true;
}


function nextPhase() {

  //实施阶段 必须上传正式清单和竣工清单才能下一步
  // const obj = phase_type.value.filter((obj) => obj.value == 1);
  const resultY = attachmentList.value.find(item => item.attachmentType == 5);//正式清单
  const resultJ = attachmentList.value.find(item => item.attachmentType == 6);//竣工清单
  // attachmentList.value

    if (!(resultY || resultJ)) {
    proxy.$modal.msgError("必须上传正式清单和竣工清单");
    return
  }


//更新当前阶段为完成
let updateParams = {
    id:currenrPhaseId.value,
    status: 2,//已完成
  }
  updatePhase(updateParams).then((response) => {
});
//插入下一个阶段的信息 状态进行中
  //立项前期 字典值为1 写死
    //实施阶段 字典值为2 写死
  //  项目绩效 3
  const filteredObjects = phase_type.value.filter((obj) => obj.value == 3);
  // personForm.value.phaseName = filteredObjects[0]?.label
  // personForm.value.phaseId = filteredObjects[0]?.value
let params = {
    projectNo: projectNo.value,
    phaseId: 3,//立项前期
    status: 1,//进行中
    phaseName: filteredObjects[0]?.label
  }
  addPhase(params).then((response) => {
    
  });
  proxy.$modal.msgSuccess("提交成功");
  // getCurrPhase(projectNo.value)

  status.value = 2
  

}


function getCurrPhase(projectNo){//查询当前阶段有无完成
  let currPhase = {
    projectNo: projectNo,
    phaseId:2//实施阶段 0
  }
  getStatus(currPhase).then((response) => {
    console.log("当前阶段信息",response);
     if(response.data == null){
    //  currenrPhaseId.value = response.data.id
     }else{
      status.value = response.data.status
      currenrPhaseId.value = response.data.id
     }
  });
}

/** 提交按钮 */
function submitForm(type) {

  form.value.participanList = personList.value;
  form.value.current = type  //type为1 保存当前内容 不提交到下一步 3则提交到下一步
  //预合同清单为1  正式清单为5
  const resultY = attachmentList.value.find(item => item.attachmentType == 1);
  const resultZ = attachmentList.value.find(item => item.attachmentType == 5);find
  // // 查找 postId 为 5 岗位id为5的是销售负责人 
  // const result = personList.value.find(item => item.postId === 5);

  const result = personList.value.find(item => item.postId === 5);

  // if (!result) {
  //   proxy.$modal.msgError("请先完善参与人员信息，至少添加一名销售负责人");
  //   return
  // }


  // //立项前期阶段 需要添加项目经理id 2 销售 9 商务 7 财务 6
  // result = attachmentList.value.find(item => item.postId === 2);
  console.log("resultY", resultY, resultZ);
  if (!(resultY || resultZ)) {
    proxy.$modal.msgError("请添加预合同清单或正式清单");
    return
  }

  // //预合同清单为1  正式清单为5
  // const resultY = attachmentList.value.find(item => item.attachmentType == 1);
  // const resultZ = attachmentList.value.find(item => item.attachmentType == 5);
  // // // 查找 postId 为 5 岗位id为5的是销售负责人 
  // // const result = personList.value.find(item => item.postId === 5);

  // // //立项前期阶段 需要添加项目经理id 2 销售 9 商务 7 财务 6
  // // result = attachmentList.value.find(item => item.postId === 2);

  // console.log("resultY",resultY,resultZ);

  // if (!(resultY || resultZ)) {
  //   proxy.$modal.msgError("请添加预合同清单或正式清单");
  //   return
  // }
  // return
  proxy.$refs["projectRef"].validate((valid) => {

    if (valid) {
      if (form.value.projectNo != null) {
        updateProject(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProject(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}



/** 提交按钮 */
function submitPersonFormback() {

  console.log("personForm", personForm.value);

  proxy.$refs["participanRef"].validate((valid, errors) => {
    if (!valid) {
      proxy.$modal.msgError("请先完善参与人员信息，至少添加一名销售负责人");
      return;
    }  
    // 验证通过，处理数据
    try {
      if (personForm.value.id != null && personForm.value.id != undefined) {
        // 查找是否有匹配的 id
        const index = personList.value.findIndex(item => item.id === personForm.value.id);
        if (index !== -1) {
          // 如果找到匹配的 id，替换对应下标的数据
          personList.value[index] = { ...personForm.value }; // 使用扩展运算符创建新对象以避免引用问题
        } else {
          // 如果没有找到匹配的 id，直接添加到列表中
          personList.value.push({ ...personForm.value });
        }
      } else {
        // 如果 id 不存在，直接添加到列表中
        personList.value.push({ ...personForm.value });
      }

      // 关闭操作窗口
      openOper.value = false;

      // 提示成功
      proxy.$modal.msgSuccess("操作成功");
    } catch (error) {
      // 捕获错误并提示用户
      console.error("操作失败", error);
      proxy.$modal.msgError("操作失败，请稍后再试");
    }
  });
}



/** 提交按钮 */
function submitPersonForm() {
  proxy.$refs["participanRef"].validate(valid => {
    if (valid) {
      personForm.value.projectNo = projectNo.value
      if (personForm.value.id != null) {
        updateParticipan(personForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openOper.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addParticipan(personForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openOper.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}



function submitPhaseForm() {
  console.log("");

}

/** 删除按钮操作 */
function handleDelete(row) {
  const _projectNos = row.projectNo || ids.value;
  proxy.$modal
    .confirm('是否确认删除绩效基本信息编号为"' + _projectNos + '"的数据项？')
    .then(function () {
      return delProject(_projectNos);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/project/export",
    {
      ...queryParams.value,
    },
    `project_${new Date().getTime()}.xlsx`
  );
}

function getCompanys() {
  getCompanyList(queryParams.value).then((response) => {
    companyList.value = response.data.map(item => ({
      ...item, // 保留原始属性
      value: item.id, // 添加 value 字段
      label: item.companyName, // 添加 label 字段
    }));
  });
  getFinanceList(queryParams.value).then((response) => {
    financeList.value = response.data.map(item => ({
      ...item, // 保留原始属性
      value: item.finance, // 添加 value 字段
      label: item.finance, // 添加 label 字段
    }));
  });

}

function getCurrentDateTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};


function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day}`;
};

getList();
getCompanys();
initData()
</script>
